// Copyright 2019 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package main

import (
	"bytes"
	"os"
	"text/template"
	"time"

	"github.com/juju/juju/controller"
	"github.com/juju/juju/internal/pki"
)

const count int = 8

type keyPair struct {
	X509       []byte
	PrivateKey []byte
}

type paramSet struct {
	GeneratedAt string
	CA          []keyPair
	Server      []keyPair
	OtherCA     []keyPair
}

func main() {
	params := paramSet{
		GeneratedAt: time.Now().Format(time.RFC822),
	}
	for i := 0; i < count; i++ {
		caSigner, err := pki.DefaultKeyProfile()
		if err != nil {
			panic(err)
		}

		caCert, err := pki.NewCA("juju testing", caSigner)
		if err != nil {
			panic(err)
		}

		authority, err := pki.NewDefaultAuthority(caCert, caSigner)
		if err != nil {
			panic(err)
		}

		caCertPem, caKeyPem, err := authority.ToPemParts()
		if err != nil {
			panic(err)
		}
		params.CA = append(params.CA, keyPair{caCertPem, caKeyPem})

		leaf, err := authority.LeafRequestForGroup("juju-server").
			AddDNSNames(controller.DefaultDNSNames...).
			Commit()
		if err != nil {
			panic(err)
		}

		leafCertPem, leafKeyPem, err := leaf.ToPemParts()
		if err != nil {
			panic(err)
		}

		params.Server = append(params.Server, keyPair{leafCertPem, leafKeyPem})
	}

	for i := 0; i < count; i++ {
		caSigner, err := pki.DefaultKeyProfile()
		if err != nil {
			panic(err)
		}

		caCert, err := pki.NewCA("juju testing", caSigner)
		if err != nil {
			panic(err)
		}

		authority, err := pki.NewDefaultAuthority(caCert, caSigner)
		if err != nil {
			panic(err)
		}

		caCertPem, caKeyPem, err := authority.ToPemParts()
		if err != nil {
			panic(err)
		}
		params.OtherCA = append(params.OtherCA, keyPair{caCertPem, caKeyPem})

	}

	buf := &bytes.Buffer{}
	err := outputTemplate.Execute(buf, params)
	if err != nil {
		panic(err)
	}

	err = os.WriteFile("certs_generated.go", buf.Bytes(), 0664)
	if err != nil {
		panic(err)
	}
}

var outputTemplate = template.Must(template.New("").Parse(`// Copyright 2019 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

// MACHINE GENERATED BY github.com/juju/juju/generate/certgen. DO NOT EDIT.

package testing

// Generated on {{.GeneratedAt}}

var generatedCA = []struct {
	certPEM string
	keyPEM  string
}{
{{range .CA}}	{ {{.X509 | printf "%q"}}, {{.PrivateKey | printf "%q"}} },
{{end}}
}

// generatedServer contains server certs that matches a CA at the same index in generatedCA
var generatedServer = []struct {
	certPEM string
	keyPEM  string
}{
{{range .Server}}	{ {{.X509 | printf "%q"}}, {{.PrivateKey | printf "%q"}} },
{{end}}
}

var otherCA = []struct {
	certPEM string
	keyPEM  string
}{
{{range .OtherCA}}	{ {{.X509 | printf "%q"}}, {{.PrivateKey | printf "%q"}} },
{{end}}
}
`))
